package com.sayice.robotconflict.game.handler;

import com.alibaba.fastjson2.JSONObject;
import com.sayice.robotconflict.game.Game;
import com.sayice.robotconflict.game.msg.Message;
import com.sayice.robotconflict.game.msg.data.receive.MoveInfo;
import com.sayice.robotconflict.game.object.Player;
import com.sayice.robotconflict.game.object.property.Direction;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * 对局消息处理器
 *
 * @author shubing
 */
@Slf4j
public class GameHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        Object[] playerAndMsg = (Object[]) msg;
        Player player = (Player) playerAndMsg[0];
        Message message = (Message) playerAndMsg[1];
        if ("game".equals(message.getType())) {
            if (player.state.get() != Player.State.GAMING) {
                return;
            }
            switch (message.getAction()) {
                case "move":
                    if (player.robot == null) {
                        break;
                    }
                    MoveInfo moveInfo = ((JSONObject) message.getData()).to(MoveInfo.class);
                    Direction direction = moveInfo.getDirection();
                    if (direction != null) {
                        player.robot.direction.set(direction.getX(), direction.getY());
                    }
                    player.robot.nextSpeed = Math.min(moveInfo.getSpeed(), Game.ROBOT_MAX_SPEED);
                    break;
                case "attack":
                    if (player.robot == null) {
                        break;
                    }
                    player.robot.attack();
                    break;
                case "changeControl":
                    int seq = ((int) message.getData());
                    player.setControl(seq);
                    break;
                case "changeSurrender":
                    player.team.changeSurrender(player);
                    break;
                default:
                    break;
            }
        } else {
            ctx.fireChannelRead(playerAndMsg);
        }
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("NettyHandler Exception from " + ctx.channel().remoteAddress(), cause);
        ctx.channel().close();
    }
}
